#!/bin/bash

readonly prefix=("jpg" "jpeg" "png" "bmp")
# base_dir="`dirname $1`/`basename $1`/"

# 获取文件列表
get_image_files(){
	base_dir="`dirname $1`/`basename $1`/"
	#echo "hello"
	for f in `ls $base_dir`
	do
		#echo "hello"
		echo "f: $f"
		for p in "${prefix[@]}"
		do
			echo "$p"
			#len_before=${#f}
			#f_after=${f%"$p"}
			#len_after=${#f_after}

			#if [ $len_before -ne $len_after ]
			if [[ $f =~ $p ]]
			then
				file_list[$index]="$base_dir$f"
				echo "获取图片：$base_dir$f 成功"
				let index=index+1
				break				
			fi
		done
	done
}

# 产生配置文件
gen_file(){
	my_wp_file="wall_paper_config_$(date +%Y-%m-%d-%k-%M).xml"
	my_wp_file="$basedir$my_wp_file"

	cat /dev/null > $my_wp_file
	
	echo -e "<background>" >> $my_wp_file

	echo -e "\t<starttime>" >> $my_wp_file
	echo -e "\t\t<year>$(date +%Y)</year>" >> $my_wp_file
	echo -e "\t\t<month>$(date +%m)</month>" >> $my_wp_file
	echo -e "\t\t<day>$(date +%d)</day>" >> $my_wp_file
	echo -e "\t\t<hour>$(date +%k)</hour>" >> $my_wp_file
	echo -e "\t\t<minute>$(date +%M)</minute>" >> $my_wp_file
	echo -e "\t</starttime>" >> $my_wp_file

	index_=0
	len=${#file_list[@]}
	for f in "${file_list[@]}"
	do
		if [ $index_ -eq $((len-1)) ]
			then
				fn=${file_list[0]}
			else
				fn=${file_list[$index_+1]}
		fi
		
		echo -e "\t<static>" >> $my_wp_file
		echo -e "\t\t<duration>${STAY:=300}</duration>" >> $my_wp_file
		echo -e "\t\t<file>$f</file>" >> $my_wp_file
		echo -e "\t</static>" >> $my_wp_file
		echo -e "\t<transition>" >> $my_wp_file
		echo -e "\t\t<duration>${DURATION:=3}</duration>" >> $my_wp_file
		echo -e "\t\t<from>$f</from>" >> $my_wp_file
		echo -e "\t\t<to>$fn</to>" >> $my_wp_file
		echo -e "\t</transition>" >> $my_wp_file

		let index_=$index_+1

	done
	
	echo -e "</background>" >> $my_wp_file
}

help(){
     echo
     echo "命令格式：`basename $0` [OPTION] -f Filepath"
     echo "指定图片目录，目录下的图片将作为动态更换的壁纸"
     echo
     echo -e "-f[Filepath]\t 图像文件目录"
     echo -e "-d[Duration]\t 图像切换时长，默认3s"
     echo -e "-s[StayTime]\t 图像停留时长，默认300s"
     echo
     exit 1
 }

while getopts f:s:d: OPTION
do
	case "$OPTION" in
	f)
		FILE_PATH="$OPTARG"
		;;
	s)
		STAY="$OPTARG"
		;;
	d)	
		DURATION="$OPTARG"
		;;
	*)
		help
		;;
	esac
done

if [ -z "$FILE_PATH" ]
then
	help
fi

if [ -d $FILE_PATH ]
then
	get_image_files $FILE_PATH

	file_count=${#file_list[@]}
	
	if [ $file_count -gt 0 ]
	then
		echo "产生壁纸配置文件"
		gen_file
	else
		echo "目录$FILE_PATH中不存在图片文件"
	fi
else
	echo "不存在目录：$FILE_PATH"
fi
